package net.celisdelafuente.java.Acacia.entity;

import java.sql.SQLException;
import java.util.ArrayList;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName="publishers")
public class Publisher {
	
	public static final String ID_FIELD_NAME = "id";
	public static final String NAME_FIELD_NAME = "name";
	
	@DatabaseField(columnName = ID_FIELD_NAME, generatedId = true)
	private int id;
	
	@DatabaseField(columnName = NAME_FIELD_NAME, canBeNull = false)
	private String name;
	
	public Publisher() {
		// Mandatory empty constructor.
	}
	
	public Publisher(String name) {
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	@SuppressWarnings("deprecation")
	public Publisher getByName(ConnectionSource conn,
			Dao<Publisher, Integer> dao, String name) {
		Publisher p = this;
		if(!name.isEmpty()) {
			ArrayList<Publisher> publisher = new ArrayList<Publisher>();
			QueryBuilder<Publisher, Integer> qb = dao.queryBuilder();
			try {
				qb.where().eq(Publisher.NAME_FIELD_NAME, name);
				qb.limit(1);
				PreparedQuery<Publisher> pq = qb.prepare();
				publisher = (ArrayList<Publisher>)dao.query(pq);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(!publisher.isEmpty())
				p=publisher.get(0);
		}		
		return p;
	}
}
